import 'package:bruno/bruno.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import './index.dart';

class ChartPage extends GetView<ChartController> {
  const ChartPage({super.key});

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(length: 2, child: Scaffold(
      appBar: _buildAppBar(context),
      body: _buildBody(context),
    ));
  }

  TabBar _buildBarBottom(BuildContext context) {
    return TabBar(
      tabs: const [Tab(text: "支出"), Tab(text: "收入")],
      onTap: (index) {
        controller.switchType(index + 1);
      },
    );
  }


  BrnAppBar _buildAppBar(BuildContext context) {
    return BrnAppBar(
      automaticallyImplyLeading: false,

      actions: InkWell(
        child: Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Obx((){
              String dateFormat = "yyyy年MM月";
              if (controller.state.dateType == 2) {
                dateFormat = "yyyy年";
              }
              return Text(DateUtil.formatDate(controller.state.currentDate, format: dateFormat));
            }),
            const Padding(
                padding: EdgeInsets.only(left: 1),
                child: Icon(Icons.keyboard_arrow_down))
          ],
        ),
        onTap: () async {
          String dateFormat = "yyyy年,MMMM月";
          if (controller.state.dateType == 2) {
            dateFormat = "yyyy年";
          }
          BrnDatePicker.showDatePicker(
            context,
            dateFormat: dateFormat,
            pickerMode: BrnDateTimePickerMode.date,
            initialDateTime: controller.state.currentDate,
            minuteDivider: 30,
            pickerTitleConfig: BrnPickerTitleConfig.Default,
            onConfirm: (dateTime, list) {
              controller.switchDate(dateTime);
            },
            onCancel: () {
              return false;
            },
          );
        },
      ),
      leadingWidth: 120,
      leading: Container(
        margin: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.black),
          borderRadius: const BorderRadius.all(
            Radius.circular(5)
          )
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(child: InkWell(
              child: Obx(() => Container(
                color: controller.state.dateType == 1 ? Colors.black : Colors.transparent,
                alignment: Alignment.center,
                child: const Text("月"),
              )),
              onTap: () {
                controller.switchDateType(1);
              },
            )),
            Expanded(child: InkWell(
              child: Obx(() => Container(
                color: controller.state.dateType == 2 ? Colors.black : Colors.transparent,
                alignment: Alignment.center,
                child: const Text("年"),
              )),
              onTap: () {
                controller.switchDateType(2);
              },
            ))
          ],
        ),
      ),
      bottom: _buildBarBottom(context),
    );
  }

  Widget _buildBody(BuildContext context) {
    return TabBarView(
        physics: const NeverScrollableScrollPhysics(),
        children: [
          _buildExpend(),
          _buildIncome(),
        ]
    );
  }

  // 收入
  Widget _buildIncome() {
    return Obx(() {
      if (controller.state.type == 2) {
        List<FlSpot> list = [];
        int length = controller.state.chartData.length;
        for(int i = 0;i<length;i++) {
          list.add(FlSpot(i+1, controller.state.chartData[i]));
        }
        return SingleChildScrollView(
          child: Container(
            color: const Color.fromRGBO(250, 250, 250, 1),
            padding: const EdgeInsets.only(left: 15, right: 15,bottom: 30),
            child: Column(
              children: [
                SizedBox(
                  height: 200,
                  child: LineChart(
                      LineChartData(
                        gridData: FlGridData(
                          show: false,
                        ),
                        titlesData: FlTitlesData(
                          show: true,
                          rightTitles: AxisTitles(
                            sideTitles: SideTitles(showTitles: false),
                          ),
                          topTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: true,
                              reservedSize: 50,
                              interval: length > 12 ? 4 : 1,
                            ),
                          ),
                          bottomTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: false,
                            ),
                          ),
                          leftTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: false,
                            ),
                          ),
                        ),
                        minY: 0,
                        borderData: FlBorderData(
                            show: false
                        ),
                        lineTouchData: LineTouchData(
                            touchTooltipData: LineTouchTooltipData(
                                showOnTopOfTheChartBoxArea: true,
                                fitInsideVertically: true,
                                fitInsideHorizontally: true,
                                getTooltipItems: (List<LineBarSpot> touchedSpots) {
                                  List<LineTooltipItem> tooltipItems  = [];
                                  String date = "";
                                  if (controller.state.dateType ==1) {
                                    date = DateUtil.formatDate(controller.state.currentDate, format: "yyyy-MM-");
                                  } else if (controller.state.dateType ==2) {
                                    date = DateUtil.formatDate(controller.state.currentDate, format: "yyyy-");
                                  }
                                  for(LineBarSpot spot in touchedSpots) {
                                    tooltipItems.add(LineTooltipItem(
                                        "${date + spot.x.toStringAsFixed(0).padLeft(2, '0')}\n￥${spot.y}",
                                        const TextStyle(color: Color(0xffFF4964))
                                    ));
                                  }
                                  return tooltipItems;
                                }
                            )
                        ),
                        lineBarsData: [
                          LineChartBarData(
                            spots: list,
                            isCurved: false,
                            barWidth: 2,
                            isStrokeCapRound: true,
                            color: const Color(0xffFF4964),
                            dotData: FlDotData(
                              show: true,
                              checkToShowDot: (FlSpot spot, LineChartBarData barData) {
                                return spot.y > 0;
                              },
                            ),
                            belowBarData: BarAreaData(
                                show: true,
                                color: const Color(0xffFF4964).withOpacity(0.2)
                            ),
                          ),
                        ],
                      )),
                ),
                Container(
                    width: double.infinity,
                    height: 75,
                    margin: const EdgeInsets.only(top: 20),
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                        color: const Color(0xffffffff),
                        borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                        boxShadow: [
                          BoxShadow(
                              color: const Color(0xff999999).withOpacity(0.2),
                              offset: Offset.zero,
                              blurRadius: 15.0,
                              spreadRadius: 7
                          )
                        ]),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text("共计收入", style: TextStyle(fontSize: 14, color: Color(0xFF999999))),
                            Obx(() => Text("${controller.state.totalAmount}", style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF333333))))
                          ],
                        ),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text("收入笔数",style: TextStyle(fontSize: 14, color: Color(0xFF999999))),
                            Obx(() => Text("${controller.state.totalNum}",style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF333333))))
                          ],
                        ),
                        Obx(() {
                          final avgNum = (controller.state.totalAmount / controller.state.chartData.length).toStringAsFixed(2);
                          if (controller.state.dateType == 1) {
                            return Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const Text("日均收入",style: TextStyle(fontSize: 14, color: Color(0xFF999999))),
                                Text(avgNum,style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF333333))),
                              ],
                            );
                          } else if (controller.state.dateType == 2) {
                            return Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const Text("月均收入",style: TextStyle(fontSize: 14, color: Color(0xFF999999))),
                                Text(avgNum,style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF333333))),
                              ],
                            );
                          } else {
                            return const SizedBox();
                          }
                        })
                      ],
                    )
                ),
                Container(
                  width: double.infinity,
                  margin: const EdgeInsets.only(top: 20),
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                      color: const Color(0xffffffff),
                      borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                      boxShadow: [
                        BoxShadow(
                            color: const Color(0xff999999).withOpacity(0.2),
                            offset: Offset.zero,
                            blurRadius: 15.0,
                            spreadRadius: 7
                        )
                      ]),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text("收入排行", style: TextStyle(color: Color(0xFF333333), fontWeight: FontWeight.bold,  fontSize: 20)),
                      Obx(() {
                        if (controller.state.countCategory.isEmpty) {
                          return BrnAbnormalStateWidget(
                            isCenterVertical: true,
                            content: "暂无数据",
                          );
                        } else {
                          return ListView.builder(
                              itemCount: controller.state.countCategory.length,
                              shrinkWrap: true,
                              physics: const NeverScrollableScrollPhysics(),
                              itemBuilder: (context, index) {
                                final item = controller.state.countCategory[index];
                                final amount = item['amount'];
                                final percent = double.tryParse((amount / controller.state.totalAmount).toStringAsFixed(4)) ?? 0;
                                return Container(
                                  margin: const EdgeInsets.all(10),
                                  child: Column(
                                    children: [
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text("${item['categoryName']}"),
                                          Text("${(percent * 100).toStringAsFixed(2)}%"),
                                          Text("${amount.toStringAsFixed(2)}")
                                        ],
                                      ),
                                      const SizedBox(height: 5),
                                      ClipRRect(
                                        borderRadius: const BorderRadius.all(Radius.circular(10.0)),
                                        child: LinearProgressIndicator(
                                          value: percent,
                                          minHeight: 10,
                                          backgroundColor: const Color(0xffFF4964).withOpacity(0.2),
                                          valueColor: const AlwaysStoppedAnimation<Color>(Color(0xffFF4964)),
                                        ),
                                      )
                                    ],
                                  ),
                                );
                              }
                          );
                        }
                      })
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        return const SizedBox();
      }
    });
  }

  // 支出
  Widget _buildExpend() {
    return Obx(() {
      if (controller.state.type == 1) {
        List<FlSpot> list = [];
        int length = controller.state.chartData.length;
        for(int i = 0;i<length;i++) {
          list.add(FlSpot(i+1, controller.state.chartData[i]));
        }
        return SingleChildScrollView(
          child: Container(
            color: const Color.fromRGBO(250, 250, 250, 1),
            padding: const EdgeInsets.only(left: 15, right: 15,bottom: 30),
            child: Column(
              children: [
                SizedBox(
                  height: 200,
                  child: LineChart(
                      LineChartData(
                        gridData: FlGridData(
                          show: false,
                        ),
                        titlesData: FlTitlesData(
                          show: true,
                          rightTitles: AxisTitles(
                            sideTitles: SideTitles(showTitles: false),
                          ),
                          topTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: true,
                              reservedSize: 50,
                              interval: length > 12 ? 4 : 1,
                            ),
                          ),
                          bottomTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: false,
                            ),
                          ),
                          leftTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: false,
                            ),
                          ),
                        ),
                        minY: 0,
                        borderData: FlBorderData(
                            show: false
                        ),
                        lineTouchData: LineTouchData(
                          touchTooltipData: LineTouchTooltipData(
                              showOnTopOfTheChartBoxArea: true,
                              fitInsideVertically: true,
                              fitInsideHorizontally: true,
                              getTooltipItems: (List<LineBarSpot> touchedSpots) {
                                List<LineTooltipItem> tooltipItems  = [];
                                String date = "";
                                if (controller.state.dateType ==1) {
                                  date = DateUtil.formatDate(controller.state.currentDate, format: "yyyy-MM-");
                                } else if (controller.state.dateType ==2) {
                                  date = DateUtil.formatDate(controller.state.currentDate, format: "yyyy-");
                                }
                                for(LineBarSpot spot in touchedSpots) {
                                  tooltipItems.add(LineTooltipItem(
                                    "${date + spot.x.toStringAsFixed(0).padLeft(2, '0')}\n￥${spot.y}",
                                    const TextStyle(color: Color(0xFF47C6A8))
                                  ));
                                }
                                return tooltipItems;
                              }
                          )
                        ),
                        lineBarsData: [
                          LineChartBarData(
                            spots: list,
                            isCurved: false,
                            barWidth: 2,
                            isStrokeCapRound: true,
                            color: const Color(0xFF47C6A8),
                            dotData: FlDotData(
                              show: true,
                              checkToShowDot: (FlSpot spot, LineChartBarData barData) {
                                return spot.y > 0;
                              },
                            ),
                            belowBarData: BarAreaData(
                                show: true,
                                color: const Color(0xFF47C6A8).withOpacity(0.2),
                            ),
                          ),
                        ],
                      )),
                ),
                Container(
                  width: double.infinity,
                  height: 75,
                  margin: const EdgeInsets.only(top: 20),
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                      color: const Color(0xffffffff),
                      borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                      boxShadow: [
                        BoxShadow(
                            color: const Color(0xff999999).withOpacity(0.2),
                            offset: Offset.zero,
                            blurRadius: 15.0,
                            spreadRadius: 7
                        )
                      ]),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Text("共计支出", style: TextStyle(fontSize: 14, color: Color(0xFF999999))),
                          Obx(() => Text("${controller.state.totalAmount}", style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF333333))))
                        ],
                      ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Text("支出笔数",style: TextStyle(fontSize: 14, color: Color(0xFF999999))),
                          Obx(() => Text("${controller.state.totalNum}",style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF333333))))
                        ],
                      ),
                      Obx(() {
                        final avgNum = (controller.state.totalAmount / controller.state.chartData.length).toStringAsFixed(2);
                        if (controller.state.dateType == 1) {
                          return Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text("日均支出",style: TextStyle(fontSize: 14, color: Color(0xFF999999))),
                              Text(avgNum,style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF333333))),
                            ],
                          );
                        } else if (controller.state.dateType == 2) {
                          return Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text("月均支出",style: TextStyle(fontSize: 14, color: Color(0xFF999999))),
                              Text(avgNum,style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF333333))),
                            ],
                          );
                        } else {
                          return const SizedBox();
                        }
                      })
                    ],
                  ),
                ),
                Container(
                  width: double.infinity,
                  margin: const EdgeInsets.only(top: 20),
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                      color: const Color(0xffffffff),
                      borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                      boxShadow: [
                        BoxShadow(
                            color: const Color(0xff999999).withOpacity(0.2),
                            offset: Offset.zero,
                            blurRadius: 15.0,
                            spreadRadius: 7
                        )
                      ]),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text("支出排行", style: TextStyle(color: Color(0xFF333333), fontWeight: FontWeight.bold,  fontSize: 20)),
                      Obx(() {
                        if (controller.state.countCategory.isEmpty) {
                          return BrnAbnormalStateWidget(
                            isCenterVertical: true,
                            content: "暂无数据",
                          );
                        } else {
                          return ListView.builder(
                              itemCount: controller.state.countCategory.length,
                              shrinkWrap: true,
                              physics: const NeverScrollableScrollPhysics(),
                              itemBuilder: (context, index) {
                                final item = controller.state.countCategory[index];
                                final amount = item['amount'];
                                final percent = double.tryParse((amount / controller.state.totalAmount).toStringAsFixed(4)) ?? 0;
                                return Container(
                                  margin: const EdgeInsets.all(10),
                                  child: Column(
                                    children: [
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text("${item['categoryName']}"),
                                          Text("${(percent * 100).toStringAsFixed(2)}%"),
                                          Text("${amount.toStringAsFixed(2)}")
                                        ],
                                      ),
                                      const SizedBox(height: 5),
                                      ClipRRect(
                                        borderRadius: const BorderRadius.all(Radius.circular(10.0)),
                                        child: LinearProgressIndicator(
                                          value: percent,
                                          minHeight: 10,
                                          backgroundColor: const Color(0xFF47C6A8).withOpacity(0.2),
                                          valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFF47C6A8)),
                                        ),
                                      )
                                    ],
                                  ),
                                );
                              }
                          );
                        }
                      })
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        return const SizedBox();
      }
    });
  }
}
